package com.zjdiepu.www.manage.api.yw;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.zjdiepu.www.base.BaseController;
import com.zjdiepu.www.base.annotation.Add;
import com.zjdiepu.www.base.annotation.Update;
import com.zjdiepu.www.base.core.AbstractSysUser;
import com.zjdiepu.www.base.core.ApiResponse;
import com.zjdiepu.www.base.core.PageVo;
import com.zjdiepu.www.base.enums.status.BusiStatus;
import com.zjdiepu.www.base.enums.status.DpStatus;
import com.zjdiepu.www.base.enums.status.PhoneStatus;
import com.zjdiepu.www.base.enums.status.RefundStatus;
import com.zjdiepu.www.base.enums.type.DataDicType;
import com.zjdiepu.www.base.enums.type.OperateType;
import com.zjdiepu.www.base.enums.type.ResultFlagType;
import com.zjdiepu.www.base.enums.type.SortFieldType;
import com.zjdiepu.www.common.util.CollectionInitUtil;
import com.zjdiepu.www.common.util.NumberUtil;
import com.zjdiepu.www.commpent.mapper.base.OtherAttachmentsVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.AbstractYwBusinessLoanVoNewMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessBuyerVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessCarVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessDetailMapper;
import com.zjdiepu.www.commpent.mapper.yw.YwBusinessVoMapper;
import com.zjdiepu.www.commpent.mapper.yw.ZxCrediQueryDetailMapper;
import com.zjdiepu.www.ibiz.base.IOtherAttachmentsService;
import com.zjdiepu.www.ibiz.base.ISysUserService;
import com.zjdiepu.www.ibiz.cache.ICachedDictionaryService;
import com.zjdiepu.www.ibiz.file.IQiniuFileService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessBuyerService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarAreaPriceService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessCarService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessLoanService;
import com.zjdiepu.www.ibiz.yw.IYwBusinessService;
import com.zjdiepu.www.ibiz.zx.IZxCreditQueryService;
import com.zjdiepu.www.model.base.dto.SimpleDataDictionary;
import com.zjdiepu.www.model.base.dto.SysUser;
import com.zjdiepu.www.model.yw.dto.YwBusiness;
import com.zjdiepu.www.model.yw.dto.YwBusinessBuyer;
import com.zjdiepu.www.model.yw.dto.YwBusinessCar;
import com.zjdiepu.www.model.yw.dto.YwBusinessCarAreaPrice;
import com.zjdiepu.www.model.yw.dto.YwBusinessLoan;
import com.zjdiepu.www.model.yw.ext.YwBusinessBuyerExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarAreaPriceExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessCarExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessExt;
import com.zjdiepu.www.model.yw.ext.YwBusinessLoanExt;
import com.zjdiepu.www.model.yw.request.ChangeChannelRequest;
import com.zjdiepu.www.model.yw.request.YwBusinessQueryRequest;
import com.zjdiepu.www.model.yw.response.YwBusinessDetail;
import com.zjdiepu.www.model.yw.response.YwBusinessInfoResponse;
import com.zjdiepu.www.model.zx.response.ZxCreditQueryDetail;
import com.zjdiepu.www.util.ExceptionHelper;
import com.zjdiepu.www.util.YwExtHelper;

/**
 * 业务信息Controller层<br/>
 * @author xiongxiaotun<br/>
 * @time 2017年04月24日 14时43分<br/>
 * @since 1.0<br/>
 */
@RestController
@RequestMapping(value= "YwBusinessController", produces="application/json;charset=UTF-8")
@Api(tags = {"业务信息"}, produces="application/json;charset=UTF-8")
public class YwBusinessController extends BaseController {
    @Resource
    private IYwBusinessService ywBusinessService;
    @Resource
    private IZxCreditQueryService zxCreditQueryService;
    @Resource
    private IOtherAttachmentsService otherAttachmentsService;
    @Resource
    private IYwBusinessCarService ywBusinessCarService;
    @Resource
    private IYwBusinessBuyerService ywBusinessBuyerService;
    @Resource
    private IYwBusinessLoanService ywBusinessLoanService;
    @Resource
    private YwBusinessVoMapper ywBusinessVoMapper;
    @Resource
    private YwBusinessDetailMapper ywBusinessDetailMapper;
    @Resource
	private OtherAttachmentsVoMapper OtherAttachmentsVoMapper;
    @Resource
    private ZxCrediQueryDetailMapper zxCrediQueryDetailMapper;
    @Resource
    private YwBusinessBuyerVoMapper ywBusinessBuyerVoMapper;
    @Resource
    private YwBusinessCarVoMapper ywBusinessCarVoMapper;
    @Resource
    private AbstractYwBusinessLoanVoNewMapper ywBusinessLoanVoMapper;
	@Resource
	private IYwBusinessCarAreaPriceService ywBusinessCarAreaPriceService;
	@Autowired
	private IQiniuFileService iQiniuFileService;
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ICachedDictionaryService cachedDictionaryService;
	
	 /**
     * @author xiongxiaotun <br/>
     * @Title: changeChannel  <br/>
     * @Description: 修改订单类型 <br/>
     * @param changeChannelRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改订单类型", response = Boolean.class, httpMethod="POST")
    @RequestMapping("changeChannel")
    public ApiResponse changeChannel(@Validated(Update.class) @ModelAttribute ChangeChannelRequest changeChannelRequest) {
    	SysUser sysUser = (SysUser)getCurrentUser();
    	ywBusinessService.saveChangeChannel(changeChannelRequest, sysUser);
        return ApiResponse.success(true);
    }
	
	/**
     * @author xiongxiaotun <br/>
     * @Title: postList  <br/>
     * @Description: 后补资料 <br/>
     * @param ywBusinessQueryRequest
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "后补资料",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "postList", method = RequestMethod.POST)
    public ApiResponse postList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        YwExtHelper.initExt(ywBusinessQueryRequest, SortFieldType.SUBMIT_TIME);
        ywBusinessQueryRequest.setMinBusiStatus(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_ZHONG.getCode()); //资审一审中之前（包括资审一审中）
        ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.YIN_HANG_YI_FANG_KUAN.getCode());//银行已放款（包括）；
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: refuseSace <br/>
	 * @Description: 订单退回<br/>
	 * @param id
	 * @return
	 * @version V1.0  <br/>
	 */
	@ApiOperation(value = "订单退回", response = Boolean.class, httpMethod="POST", tags={"订单退回"})
	@RequestMapping(value = "refuseSace", method = RequestMethod.POST)
	public ApiResponse refuseSace(String id,HttpServletRequest request) {
		SysUser currentUser =(SysUser)getCurrentUser();
		ywBusinessService.saveRefuseSace(id, currentUser);
		return ApiResponse.success(true);
	}
	
	/**
	 * @author xiongxiaotun <br/>
	 * @Title: comitFinal <br/>
	 * @Description: 提交终审<br/>
	 * @param id
	 * @return
	 * @version V1.0  <br/>
	 */
	@ApiOperation(value = "提交终审", response = Boolean.class, httpMethod="POST", tags={"提交终审"})
	@RequestMapping(value = "comitFinal", method = RequestMethod.POST)
	public ApiResponse comitFinal(String id,HttpServletRequest request) {
		SysUser currentUser =(SysUser)getCurrentUser();
		HttpSession session = request.getSession();      
		ServletContext  application  = session.getServletContext();  
		String serverRealPath = application.getRealPath("/WEB-INF/configure/fkshConfV001.json");
		ywBusinessService.saveComitFinal(id, currentUser,serverRealPath);
		return ApiResponse.success(true);
	}
	
	 /**
     * @author xiongxiaotun <br/>
     * @Title: applayAllocation <br/>
     * @Description: 申请填写资料派单<br/>
     * @param allocationNum
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "申请填写资料派单", response = Boolean.class, httpMethod="POST", tags={"资料派单"})
    @RequestMapping(value = "applayAllocation", method = RequestMethod.POST)
    public ApiResponse applayAllocation(int allocationNum) {
    	SysUser currentUser =(SysUser)getCurrentUser();
    	ywBusinessService.updateForApplyAllocation(allocationNum, currentUser);
        return ApiResponse.success(true);
    }
	
	  
    /**
     * @author xiongxiaotun <br/>
     * @Title: checkCompleted  <br/>
     * @Description: 确认业务信息完整<br/>
     * @param id
     * @param modeId
     * @return 0.数据完整  1.业务数据信息不完整 2.购车人信息不完整 3.车辆信息不完整 4.车贷信息不完整<br/>
     *          5.身份证明资料不足 6.必须上传结婚证或单身结局证之一 7.重要原件资料不足  8.配偶签字资料不足<br/>
     *          9.居住证明资料不足 10.银行流水资料不足 11.主借人签字资料不足 <br/>
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "确认业务信息完整", response = Integer.class, httpMethod="POST")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1"),
        @ApiImplicitParam(name = "ifPhone", value = "是否需要电审", paramType="query", required = true, example="0"),
    })
    @RequestMapping(value = "checkCompleted", method = RequestMethod.POST)
    public ApiResponse checkCompleted(String id,@RequestParam(defaultValue="0") boolean ifPhone) {
    	if (StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		AbstractSysUser currentUser = getCurrentUser();
        return ywBusinessService.saveCompleted(id, currentUser, ifPhone, null);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: save  <br/>
     * @Description: 新增业务信息 <br/>
     * @param ywBusiness
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "新增业务信息", response = Boolean.class, httpMethod="POST", tags={"新增"})
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public ApiResponse save(@Validated(Add.class) @ModelAttribute YwBusiness ywBusiness) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusiness.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusiness.setModifierName(currentUser.getName());
        ywBusinessService.saveUpdateAndDelete(ywBusiness, OperateType.add);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: saveStatus  <br/>
     * @Description: 修改业务信息状态 <br/>
     * @param channelStatus
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改业务信息状态", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1"),
        @ApiImplicitParam(name = "channelType", value = "通道类型", paramType="query", required = true, example="01"),
    })
    @RequestMapping(value = "saveStatus", method = RequestMethod.POST)
    public ApiResponse saveStatus(String channelType, String id) {
    	if(StringUtils.isBlank(id) || StringUtils.isBlank(channelType)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	YwBusiness ywBusiness = new YwBusiness();
    	ywBusiness.setId(id);
    	ywBusiness.setChannelType(channelType);
    	ywBusiness.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusiness.setModifierName(currentUser.getName());
    	List<String> ids = new ArrayList<String>();
    	ids.add(id);
        ywBusinessService.updateCommonBatch(ywBusiness, ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: remove  <br/>
     * @Description: 删除业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "删除业务信息", response = Boolean.class, httpMethod="POST", tags={"删除"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "remove", method = RequestMethod.POST)
    public ApiResponse remove(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.DELETED.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: disable  <br/>
     * @Description: 禁用业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "禁用业务信息", response = Boolean.class, httpMethod="POST", tags={"禁用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "disable", method = RequestMethod.POST)
    public ApiResponse disable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.INVALID.getCode(), ids);
        return ApiResponse.success(true);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: enable <br/>
     * @Description: 启用业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "启用业务信息", response = Boolean.class, httpMethod="POST", tags={"启用"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "enable", method = RequestMethod.POST)
    public ApiResponse enable(String id) {
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
    	List<String> ids = Arrays.asList(id.split(","));
    	ywBusinessService.updateBatch(currentUser.getId(), currentUser.getName(), DpStatus.NORMAL.getCode(), ids);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: modify  <br/>
     * @Description: 修改业务信息 <br/>
     * @param ywBusiness
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "修改业务信息", response = Boolean.class, httpMethod="POST", tags={"修改"})
    @RequestMapping(value = "modify", method = RequestMethod.POST)
    public ApiResponse modify(@Validated(Update.class) @ModelAttribute YwBusiness ywBusiness) {
    	AbstractSysUser currentUser = getCurrentUser();
    	ywBusiness.setModifier(currentUser.getId()); //统一使用修改人和修改人名称来初始化
    	ywBusiness.setModifierName(currentUser.getName());
    	ywBusinessService.saveUpdateAndDelete(ywBusiness, OperateType.edit);
        return ApiResponse.success(true);
    }

    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "主键查询业务信息", response = YwBusiness.class, httpMethod="POST", tags={"主键查询"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getById", method = RequestMethod.POST)
    public ApiResponse getById(String id){
    	if(StringUtils.isBlank(id)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
       YwBusiness ywBusiness = ywBusinessService.selectById(id);
       if(null == ywBusiness) {
    	   return ApiResponse.fail(ResultFlagType.MISSING);
       }
       return ApiResponse.success(ywBusiness);
    }
    
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: getStatus  <br/>
     * @Description: 主键查询业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
	@ApiOperation(value = "获取锁定状态", response = Boolean.class, httpMethod="POST", tags={"主键查询多表"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getStatus", method = RequestMethod.POST)
	public ApiResponse getStatus(String id) {
		SysUser currentUser =(SysUser)getCurrentUser();
		YwBusiness dbYwBusiness = ywBusinessService.selectById(id);
		
		if(StringUtils.isNotBlank(dbYwBusiness.getOperatorId()) && !currentUser.getId().equals(dbYwBusiness.getOperatorId())) {
			return ApiResponse.success(true);
		}
		return ApiResponse.success(false);
	}
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: getById  <br/>
     * @Description: 主键查询业务信息<br/>
     * @param id
     * @return
     * @version V1.0  <br/>
     */
	@ApiOperation(value = "主键查询多表业务信息", response = YwBusiness.class, httpMethod="POST", tags={"主键查询多表"})
    @ApiImplicitParams({
        @ApiImplicitParam(name = "id", value = "数据主键", paramType="query", required = true, example="1")
    })
    @RequestMapping(value = "getMultiById", method = RequestMethod.POST)
	public ApiResponse getMultiById(String id) {
		if (StringUtils.isBlank(id)) {
			return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
		}
		SysUser currentUser =(SysUser)getCurrentUser();
		/*YwBusiness dbYwBusiness = ywBusinessService.selectById(id);
		
		if(StringUtils.isNotBlank(dbYwBusiness.getOperatorId()) && !currentUser.getId().equals(dbYwBusiness.getOperatorId())) {
			return ApiResponse.fail(9999, "该数据已经被他人锁定");
		}*/
		
		YwBusinessInfoResponse response = new YwBusinessInfoResponse();
		List<SimpleDataDictionary> loanBanks = cachedDictionaryService.getCachedDataDics(DataDicType.LOAN_BANK);
		response.setLoanBanks(loanBanks);
		
		List<SimpleDataDictionary>  intTypes = cachedDictionaryService.getCachedDataDics(DataDicType.INT_TYPE);
		response.setIntTypes(intTypes);
		
		YwBusinessDetail ywBusinessDetail = ywBusinessService.getMultiById(id);
		if (null == ywBusinessDetail) {
			ExceptionHelper.thow(ResultFlagType.MISSING);
		}
		response.setYwBusinessDetail(ywBusinessDetail);
		// 查询征信信息
		String creditApplyId = ywBusinessDetail.getQueryCreditApplyId();
		if (StringUtils.isNotBlank(creditApplyId)) {
			List<ZxCreditQueryDetail> zxCrediQueryDetails = zxCreditQueryService.selectMultiByApplyId(creditApplyId);
			zxCrediQueryDetailMapper.mapper(zxCrediQueryDetails);
			response.setZxCreditQuerys(zxCrediQueryDetails);
			/*for (ZxCreditQueryDetail zxCrediQueryDetail : zxCrediQueryDetails) {
				String creditPeopleType = zxCrediQueryDetail
						.getCreditPeopleType();
				SimpleDataDictionary cachedDataDic = cachedDictionaryService.getCachedDataDic(creditPeopleType, DataDicType.CREDIT_PEOPLE_TYPE);
				if (null != cachedDataDic) {
					response.addZxCreditQuery(cachedDataDic.getValue(),
							zxCrediQueryDetail);
				}
			}*/
		}
		// 查询购车人信息
		YwBusinessBuyerExt ywBusinessBuyerExt = new YwBusinessBuyerExt();
		ywBusinessBuyerExt.setBaseWhere();
		ywBusinessBuyerExt.withOutPage();
		ywBusinessBuyerExt.setBusiId(id);
		List<YwBusinessBuyer> ywBusinessBuyers = ywBusinessBuyerService
				.selectByExt(ywBusinessBuyerExt);
		for (YwBusinessBuyer ywBusinessBuyer : ywBusinessBuyers) {
			ywBusinessBuyerVoMapper.mapper(ywBusinessBuyer);
			String carManType = ywBusinessBuyer.getCarManType();
			SimpleDataDictionary cachedDataDic = cachedDictionaryService.getCachedDataDic(carManType, DataDicType.CREDIT_PEOPLE_TYPE);
			if (null != cachedDataDic) {
				response.addYwBusinessBuyer(cachedDataDic.getValue(),
						ywBusinessBuyer);
			}
		}
		// 查询车辆&车贷信息
		YwBusinessCarExt ywBusinessCarExt = new YwBusinessCarExt();
		ywBusinessCarExt.setBaseWhere();
		ywBusinessCarExt.setRows(1);// 只能返回一条数据
		ywBusinessCarExt.setBusiId(id);
		List<YwBusinessCar> ywBusinessCars = ywBusinessCarService
				.selectByExt(ywBusinessCarExt);
		if (CollectionUtils.isNotEmpty(ywBusinessCars)) {
			YwBusinessCar ywBusinessCar = ywBusinessCars.get(0);
			ywBusinessCarVoMapper.mapper(ywBusinessCar);
			response.setYwBusinessCar(ywBusinessCar);

			String carId = ywBusinessCar.getId();
			// 查询车辆&车贷信息 //只能返回一条数据
			YwBusinessLoanExt ywBusinessLoanExt = new YwBusinessLoanExt();
			ywBusinessLoanExt.setBaseWhere();
			ywBusinessLoanExt.setRows(1);// 只能返回一条数据
			ywBusinessLoanExt.setBusiId(id);
			ywBusinessLoanExt.setCarId(carId);
			ywBusinessLoanExt.setOrderSql("`CREATED` DESC");
			List<YwBusinessLoan> ywBusinessLoans = ywBusinessLoanService
					.selectByExt(ywBusinessLoanExt);
			if (CollectionUtils.isNotEmpty(ywBusinessLoans)) {
				YwBusinessLoan ywBusinessLoan = ywBusinessLoans.get(0);
				ywBusinessLoan.setCarType(ywBusinessCar.getCarType());
				ywBusinessLoanVoMapper.mapper(ywBusinessLoan);
				response.setYwBusinessLoan(ywBusinessLoan);
			}
			
			//估价
			YwBusinessCarAreaPriceExt ywBusinessCarAreaPriceExt = new YwBusinessCarAreaPriceExt();
			ywBusinessCarAreaPriceExt.setBaseWhere();
			ywBusinessCarAreaPriceExt.withOutPage();
			ywBusinessCarAreaPriceExt.setBusiId(id);
			ywBusinessCarAreaPriceExt.setCarId(carId);
			ywBusinessCarAreaPriceExt.setOrderSql("`AREA_ID` ASC");
			List<YwBusinessCarAreaPrice> ywBusinessCarAreaPrices = ywBusinessCarAreaPriceService.selectByExt(ywBusinessCarAreaPriceExt);
			if(CollectionUtils.isNotEmpty(ywBusinessCarAreaPrices)) {
				StringBuilder sb = new StringBuilder();
				sb.append("经评估，该二手车 ");
				for(YwBusinessCarAreaPrice ywBusinessCarAreaPrice : ywBusinessCarAreaPrices) {
					String price = ywBusinessCarAreaPrice.getPrice();
					sb.append(" <span class=\"gujianame\">").append(ywBusinessCarAreaPrice.getAreaName())
					.append("：</span><span class=\"gujiaprice\">")
					.append(price).append(NumberUtil.isNumber(price)?"万":"")
					.append("</span>");
				}
				response.setCarAreaPrice(sb.toString());
			}
		}
		
		YwBusiness ywBusiness = new YwBusiness();
		ywBusiness.setId(id);
		ywBusiness.setModifier(currentUser.getId());
		ywBusiness.setModifierName(currentUser.getName());
		ywBusiness.setOperatorId(currentUser.getId());
		ywBusiness.setOperatorName(currentUser.getName());
		ywBusiness.setAcceptDate(new Date());
		ywBusinessService.saveUpdateAndDelete(ywBusiness, OperateType.edit);
		
		return ApiResponse.success(response);
	}
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询业务信息 <br/>
     * @param ywBusinessExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询业务信息",response = YwBusiness.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "list", method = RequestMethod.POST)
    public ApiResponse list(@ModelAttribute YwBusinessExt ywBusinessExt){
        ywBusinessExt.notDeleted();
        PageVo page = getPage(ywBusinessExt);
        int records = ywBusinessService.countByExt(ywBusinessExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectByExt(ywBusinessExt);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: notAllocationList  <br/>
     * @Description: 查询未分配的业务信息 <br/>
     * @param ywBusinessExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "查询未分配的业务信息",response = YwBusiness.class, httpMethod="POST", tags={"列表"})
    @RequestMapping(value = "notAllocationList", method = RequestMethod.POST)
    public ApiResponse notAllocationList(@ModelAttribute YwBusinessExt ywBusinessExt){
    	SysUser sysUser =(SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessExt);
        ywBusinessExt.setBaseWhere();
        ywBusinessExt.addBusiStatus(BusiStatus.ZI_LIAO_DENG_JI.getCode());
        ywBusinessExt.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessExt.setNeedLimit(true);
        int records = ywBusinessService.countNotAllocation(ywBusinessExt);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectNotAllocation(ywBusinessExt);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: list  <br/>
     * @Description: 条件查询业务信息 <br/>
     * @param ywBusinessExt
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "条件查询业务信息",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "multiList", method = RequestMethod.POST)
    public ApiResponse multiList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser sysUser = (SysUser)getCurrentUser();
        PageVo page = getPage(ywBusinessQueryRequest);
        ywBusinessQueryRequest.setBaseWhere();
        ywBusinessQueryRequest.setBankLoan(sysUser.getLoanBank());
        ywBusinessQueryRequest.setCodeUnits(sysUser.getCodeUnits());
        ywBusinessQueryRequest.setNeedLimit(true);
        YwExtHelper.initExt(ywBusinessQueryRequest, SortFieldType.SUBMIT_TIME);
//        ywBusinessQueryRequest.addBusiStatus(BusiStatus.ZI_LIAO_DENG_JI.getCode());
//        ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.CHU_SHEN_DAN_ZHONG_SHEN_ZHONG.getCode());
        ywBusinessQueryRequest.setMaxBusiStatus(BusiStatus.ZI_SHEN_YI_SHEN_ZHONG.getCode()); //资审一审中之前（包括资审一审中）
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            for(YwBusiness ywBusines : ywBusinesss) {
            	String operatorId = ywBusines.getOperatorId();
            	if(StringUtils.isNotBlank(operatorId)) {
            		ywBusines.setLock(sysUser.getId().equals(operatorId) ? 1 : 2);
            	} else {
            		ywBusines.setLock(0);
            	}
            }
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: allocation <br/>
     * @Description: 资料登记客户派单<br/>
     * @param id
     * @param operatorId
     * @param operatorName
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "资料登记客户派单", response = Boolean.class, httpMethod="POST", tags={"资料派单"})
    @RequestMapping(value = "allocation", method = RequestMethod.POST)
    public ApiResponse allocation(String id, String operatorId, String operatorName) {
    	if(!org.apache.commons.lang3.StringUtils.isNoneBlank(id, operatorId, operatorName)) {
    		return ApiResponse.fail(ResultFlagType.PARAM_EMPTY);
    	}
    	AbstractSysUser currentUser = getCurrentUser();
        return ywBusinessService.saveAllocation(id, operatorId, operatorName, currentUser);
    }
    
    /**
     * @author xiongxiaotun <br/>
     * @Title: randomAllocation <br/>
     * @Description: 资料登记客户派单<br/>
     * @param ywBusiness
     * @return
     * @version V1.0  <br/>
     */
    @ApiOperation(value = "资料登记客户派单", response = Boolean.class, httpMethod="POST", tags={"资料派单"})
    @RequestMapping(value = "randomAllocation", method = RequestMethod.POST)
    public ApiResponse randomAllocation(int allocationNum) {
    	SysUser currentUser =(SysUser)getCurrentUser();
    	ywBusinessService.updateForRandomAllocation(allocationNum, currentUser);
        return ApiResponse.success(true);
    }
    /** 
    * @author zhangzj
    * @Title: tongrongList 
    * @Description: 通融查询业务信息
    * @param @param ywBusinessQueryRequest
    * @param @return    设定文件 
    * @return ApiResponse    返回类型 
    * @version V1.0
    * @throws 
    */
    @ApiOperation(value = "通融查询业务信息",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "tongrongList", method = RequestMethod.POST)
    public ApiResponse tongrongList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser currentUser = (SysUser)getCurrentUser();
		PageVo page = getPage(ywBusinessQueryRequest);
		ywBusinessQueryRequest.setBaseWhere();
		ywBusinessQueryRequest.setBankLoan(currentUser.getLoanBank());
        ywBusinessQueryRequest.addBusiStatus(BusiStatus.CHU_SHEN_DAN_CHU_SHEN_SHI_BAI.getCode());
        ywBusinessQueryRequest.addBusiStatus(BusiStatus.CHU_SHEN_DAN_ZHONG_SHEN_SHI_BAI.getCode());
        ywBusinessQueryRequest.addBusiStatus(BusiStatus.ZI_SHEN_YI_SHEN_SHI_BAI.getCode());
        ywBusinessQueryRequest.addBusiStatus(BusiStatus.ZI_SHEN_ER_SHEN_SHI_BAI.getCode());
        
        ywBusinessQueryRequest.addPhoneStatus(PhoneStatus.PHONE_1_FAIL.getCode());
        ywBusinessQueryRequest.addPhoneStatus(PhoneStatus.PHONE_2_FAIL.getCode());
//        ywBusinessQueryRequest.setCodeUnits(currentUser.getCodeUnits());
        int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
        page.setRecords(records);
        if (records > 0) {
            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
            ywBusinessVoMapper.mapper(ywBusinesss);
            page.setRows(ywBusinesss);
        } else {
            page.setRows(CollectionInitUtil.emptyList());
        }
        return ApiResponse.success(page);
    }
    
    @ApiOperation(value = "获取曾经逾期和逾期数据列表",response = YwBusiness.class, httpMethod="POST", tags={"多表查询"})
    @RequestMapping(value = "overdueList", method = RequestMethod.POST)
    public ApiResponse overdueList(@Validated @ModelAttribute YwBusinessQueryRequest ywBusinessQueryRequest){
    	SysUser currentUser = (SysUser)getCurrentUser();
		PageVo page = getPage(ywBusinessQueryRequest);
		ywBusinessQueryRequest.setBaseWhere();
		ywBusinessQueryRequest.setBankLoan(currentUser.getLoanBank());
		ywBusinessQueryRequest.addRefundStatuss(RefundStatus.YU_QI.getCode());
		ywBusinessQueryRequest.addRefundStatuss(RefundStatus.CENG_JIN_YU_QI.getCode());
		  int records = ywBusinessService.countMultiByExt(ywBusinessQueryRequest);
	        page.setRecords(records);
	        if (records > 0) {
	            List<YwBusiness> ywBusinesss = ywBusinessService.selectMultiByExt(ywBusinessQueryRequest);
	            ywBusinessVoMapper.mapper(ywBusinesss);
	            page.setRows(ywBusinesss);
	        } else {
	            page.setRows(CollectionInitUtil.emptyList());
	        }
	        return ApiResponse.success(page);
    }
}
